<template>
  <el-dialog
    v-model="dialogVisible"
    title="订单详情"
    width="800px"
    destroy-on-close
    class="order-detail-dialog"
    @closed="resetForm"
  >
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    <div v-else class="order-detail-container">
      <!-- 订单状态 -->
      <div class="detail-header">
        <div class="order-status">
          <el-tag :type="getStatusTagType(orderData.status)" size="large">
            {{ getOrderStatusText(orderData.status) }}
          </el-tag>
        </div>
        <div class="order-number">
          订单号：{{ orderData.number }}
        </div>
      </div>

      <!-- 顾客信息 -->
      <div class="detail-section">
        <div class="section-title">
          <i class="el-icon-user"></i>
          <span>顾客信息</span>
        </div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">姓名：</span>
            <span class="value">{{ orderData.consignee }}</span>
          </div>
          <div class="info-item">
            <span class="label">电话：</span>
            <span class="value">{{ orderData.phone }}</span>
          </div>
          <div class="info-item address">
            <span class="label">地址：</span>
            <span class="value">{{ orderData.address }}</span>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="detail-section">
        <div class="section-title">
          <i class="el-icon-document"></i>
          <span>订单信息</span>
        </div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ orderData.orderTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付状态：</span>
            <span class="value">
              <el-tag 
                :type="orderData.payStatus === 1 ? 'success' : orderData.payStatus === 2 ? 'info' : 'danger'"
                effect="plain"
                size="small"
              >
                {{ getPaymentStatusText(orderData.payStatus) }}
              </el-tag>
            </span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ orderData.payMethod === 1 ? '微信支付' : '支付宝支付' }}</span>
          </div>
          <div class="info-item">
            <span class="label">餐具数量：</span>
            <span class="value">
              {{ orderData.tablewareStatus === 1 ? '按餐量提供' : `${orderData.tablewareNumber || 0}套` }}
            </span>
          </div>
          <div class="info-item full-width">
            <span class="label">备注：</span>
            <span class="value">{{ orderData.remark || '无' }}</span>
          </div>
        </div>
      </div>

      <!-- 菜品信息 -->
      <div class="detail-section">
        <div class="section-title">
          <i class="el-icon-food"></i>
          <span>菜品信息</span>
        </div>
        <el-table
          :data="orderData.orderDetailList || []"
          style="width: 100%"
          size="small"
          border
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="name" label="商品名称" min-width="180" />
          <el-table-column label="数量" width="80" align="center">
            <template #default="{ row }">
              {{ row.copies || row.number || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120" align="right">
            <template #default="{ row }">
              <span class="price">￥{{ formatPrice(row.amount) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 费用信息 -->
      <div class="detail-section">
        <div class="price-summary">
          <div class="price-item">
            <span class="label">商品金额：</span>
            <span class="value">￥{{ formatPrice(orderData.amount - (orderData.packAmount || 0)) }}</span>
          </div>
          <div class="price-item">
            <span class="label">打包费：</span>
            <span class="value">￥{{ formatPrice(orderData.packAmount || 0) }}</span>
          </div>
          <div class="price-item total">
            <span class="label">实付金额：</span>
            <span class="value highlight">￥{{ formatPrice(orderData.amount) }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        
        <!-- 待付款状态显示取消 -->
        <template v-if="orderData.status === 1">
          <el-button type="warning" @click="handleCancel">取消订单</el-button>
        </template>
        
        <!-- 只有待接单状态显示接单和拒单 -->
        <template v-if="orderData.status === 2">
          <el-button type="danger" @click="handleReject">拒单</el-button>
          <el-button type="primary" @click="handleConfirm">接单</el-button>
        </template>
        
        <!-- 只有已接单状态显示派送和取消 -->
        <template v-if="orderData.status === 3">
          <el-button type="warning" @click="handleCancel">取消订单</el-button>
          <el-button type="primary" @click="handleDeliver">派送</el-button>
        </template>
        
        <!-- 只有派送中状态显示完成和取消 -->
        <template v-if="orderData.status === 4">
          <el-button type="warning" @click="handleCancel">取消订单</el-button>
          <el-button type="primary" @click="handleComplete">完成</el-button>
        </template>
        
        <!-- 已完成状态显示取消 -->
        <template v-if="orderData.status === 5">
          <el-button type="warning" @click="handleCancel">取消订单</el-button>
        </template>
      </div>
    </template>
  </el-dialog>

  <!-- 拒单原因弹窗 -->
  <el-dialog
    v-model="rejectDialogVisible"
    title="拒单原因"
    width="500px"
    append-to-body
    destroy-on-close
  >
    <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules">
      <el-form-item prop="rejectionReason" label="拒单原因" label-width="100px">
        <el-select
          v-model="rejectForm.rejectionReason"
          placeholder="请选择拒单原因"
          style="width: 100%"
          :teleported="false"
        >
          <el-option label="商品已售完" value="商品已售完" />
          <el-option label="超出配送范围" value="超出配送范围" />
          <el-option label="店铺已打烊" value="店铺已打烊" />
          <el-option label="其他原因" value="其他原因" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 取消原因弹窗 -->
  <el-dialog
    v-model="cancelDialogVisible"
    title="取消订单"
    width="500px"
    append-to-body
    destroy-on-close
  >
    <el-form :model="cancelForm" ref="cancelFormRef" :rules="cancelRules">
      <el-form-item prop="cancelReason" label="取消原因" label-width="100px">
        <el-select
          v-model="cancelForm.cancelReason"
          placeholder="请选择取消原因"
          style="width: 100%"
          @change="handleCancelReasonChange"
          :teleported="false"
        >
          <el-option label="商品已售完" value="商品已售完" />
          <el-option label="顾客取消" value="顾客取消" />
          <el-option label="店铺已打烊" value="店铺已打烊" />
          <el-option label="其他原因" value="其他原因" />
        </el-select>
      </el-form-item>
      <el-form-item 
        v-if="cancelForm.cancelReason === '其他原因'" 
        prop="customCancelReason" 
        label="具体原因" 
        label-width="100px"
      >
        <el-input
          v-model="cancelForm.customCancelReason"
          type="textarea"
          :rows="3"
          placeholder="请输入具体的取消原因"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCancel">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ORDER_STATUS, PAYMENT_STATUS, ORDER_STATUS_TEXT, PAYMENT_STATUS_TEXT, ORDER_STATUS_TAG_TYPE } from '../constants'
import orderApi from '@/api/order'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  orderId: {
    type: [Number, String],
    default: null
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

// 对话框显示状态
const dialogVisible = ref(false)
// 拒单对话框状态
const rejectDialogVisible = ref(false)
// 取消订单对话框状态
const cancelDialogVisible = ref(false)
// 加载状态
const loading = ref(false)
// 订单数据
const orderData = reactive({
  id: null,
  number: '',
  status: null,
  payStatus: null,
  payMethod: null,
  amount: 0,
  packAmount: 0,          // 打包费
  tablewareNumber: 0,     // 餐具数量
  tablewareStatus: null,  // 餐具数量状态
  consignee: '',
  phone: '',
  address: '',
  orderTime: '',
  remark: '',
  orderDetailList: []
})

// 拒单表单
const rejectFormRef = ref(null)
const rejectForm = reactive({
  id: null,
  rejectionReason: ''
})
const rejectRules = {
  rejectionReason: [
    { required: true, message: '请选择拒单原因', trigger: 'change' }
  ]
}

// 取消订单表单
const cancelFormRef = ref(null)
const cancelForm = reactive({
  id: null,
  cancelReason: '',
  customCancelReason: ''
})
const cancelRules = {
  cancelReason: [
    { required: true, message: '请选择取消原因', trigger: 'change' }
  ],
  customCancelReason: [
    { 
      required: true, 
      message: '请输入具体的取消原因', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (cancelForm.cancelReason === '其他原因' && !value) {
          callback(new Error('请输入具体的取消原因'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 监听订单详情事件，接收从通知传递的数据
const handleOpenOrderDetail = (event) => {
  if (event && event.detail) {
    console.log('订单详情组件收到事件:', event.detail);
    
    // 从服务器获取最新数据
    if (event.detail.orderId) {
      // 设置orderId并获取详情
      props.orderId = event.detail.orderId;
      fetchOrderDetail();
    }
  }
};

// 监听visible变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val && props.orderId) {
    console.log('订单详情对话框打开，订单ID:', props.orderId)
    // 清空之前的数据
    resetForm()
    // 从服务器获取最新数据
    fetchOrderDetail()
  }
})

// 监听orderId变化
watch(() => props.orderId, (newId) => {
  if (newId && dialogVisible.value) {
    console.log('订单ID变化，重新获取详情:', newId)
    fetchOrderDetail()
  }
})

// 监听dialogVisible变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!props.orderId) {
    console.warn('没有订单ID，无法获取订单详情')
    return
  }
  
  loading.value = true
  try {
    console.log('开始获取订单详情，订单ID:', props.orderId)
    const res = await orderApi.details(props.orderId)
    console.log('API响应:', res)
    
    if (res && res.code === 1 && res.data) {
      console.log('获取到订单详情:', res.data)
      
      // 直接赋值整个对象
      Object.assign(orderData, {
        id: res.data.id || null,
        number: res.data.number || '',
        status: res.data.status || null,
        payStatus: res.data.payStatus || null,
        payMethod: res.data.payMethod || null,
        amount: res.data.amount || 0,
        packAmount: res.data.packAmount || 0,
        tablewareNumber: res.data.tablewareNumber || 0,
        tablewareStatus: res.data.tablewareStatus || null,
        consignee: res.data.consignee || '',
        phone: res.data.phone || '',
        address: res.data.address || '',
        orderTime: res.data.orderTime || '',
        remark: res.data.remark || '',
        orderDetailList: res.data.orderDetailList || []
      })
      
      console.log('订单数据已更新:', orderData)
    } else {
      console.error('获取订单详情失败:', res?.msg || '响应格式错误')
      ElMessage.error(res?.msg || '获取订单详情失败，请重试')
    }
  } catch (error) {
    console.error('获取订单详情出错:', error)
    ElMessage.error('获取订单详情出错: ' + (error.response?.data?.msg || error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('open-order-detail', handleOpenOrderDetail);
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('open-order-detail', handleOpenOrderDetail);
});

// 获取订单状态文本
const getOrderStatusText = (status) => {
  return ORDER_STATUS_TEXT[status] || '未知状态'
}

// Obtain payment status text
const getPaymentStatusText = (status) => {
  return PAYMENT_STATUS_TEXT[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  return ORDER_STATUS_TAG_TYPE[status] || 'info'
}

// 格式化价格
const formatPrice = (price) => {
  return parseFloat(price).toFixed(2)
}

// 接单
const handleConfirm = () => {
  ElMessageBox.confirm('确定接受此订单吗？', '确认接单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await orderApi.confirm({ id: orderData.id })
      if (res.code === 1) {
        ElMessage.success('接单成功')
        dialogVisible.value = false
        emit('refresh')
      }
    } catch (error) {
      console.error('接单失败:', error)
    }
  }).catch(() => {})
}

// 拒单
const handleReject = () => {
  rejectForm.id = orderData.id
  rejectDialogVisible.value = true
}

// 确认拒单
const confirmReject = async () => {
  rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await orderApi.rejection(rejectForm)
        if (res.code === 1) {
          ElMessage.success('拒单成功')
          rejectDialogVisible.value = false
          dialogVisible.value = false
          emit('refresh')
        }
      } catch (error) {
        console.error('拒单失败:', error)
      }
    }
  })
}

// 取消订单
const handleCancel = () => {
  cancelForm.id = orderData.id
  cancelForm.cancelReason = ''
  cancelForm.customCancelReason = ''
  cancelDialogVisible.value = true
}

// 确认取消订单
const confirmCancel = async () => {
  cancelFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 如果选择的是其他原因，使用自定义理由
        const cancelReason = cancelForm.cancelReason === '其他原因' 
          ? cancelForm.customCancelReason 
          : cancelForm.cancelReason
          
        const res = await orderApi.cancel({ 
          id: cancelForm.id, 
          cancelReason: cancelReason 
        })
        if (res.code === 1) {
          ElMessage.success('取消订单成功')
          cancelDialogVisible.value = false
          dialogVisible.value = false
          emit('refresh')
        }
      } catch (error) {
        console.error('取消订单失败:', error)
      }
    }
  })
}

// 派送订单
const handleDeliver = () => {
  ElMessageBox.confirm('确定将此订单派送吗？', '派送订单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await orderApi.delivery(orderData.id)
      if (res.code === 1) {
        ElMessage.success('订单已派送')
        dialogVisible.value = false
        emit('refresh')
      }
    } catch (error) {
      console.error('派送订单失败:', error)
    }
  }).catch(() => {})
}

// 完成订单
const handleComplete = () => {
  ElMessageBox.confirm('确定此订单已完成吗？', '完成订单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await orderApi.complete(orderData.id)
      if (res.code === 1) {
        ElMessage.success('订单已完成')
        dialogVisible.value = false
        emit('refresh')
      }
    } catch (error) {
      console.error('完成订单失败:', error)
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  Object.assign(orderData, {
    id: null,
    number: '',
    status: null,
    payStatus: null,
    payMethod: null,
    amount: 0,
    packAmount: 0,
    tablewareNumber: 0,
    tablewareStatus: null,
    consignee: '',
    phone: '',
    address: '',
    orderTime: '',
    remark: '',
    orderDetailList: []
  })
}

// 处理取消原因变化
const handleCancelReasonChange = () => {
  // 清空自定义理由输入
  if (cancelForm.cancelReason !== '其他原因') {
    cancelForm.customCancelReason = ''
  }
}
</script>

<style scoped>
.order-detail-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.order-detail-dialog :deep(.el-dialog__title) {
  font-weight: bold;
  font-size: 18px;
}

.order-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.order-detail-container {
  max-height: 600px;
  overflow-y: auto;
  padding: 0 10px;
}

.loading-container {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e4e7ed;
}

.order-status {
  font-size: 16px;
}

.order-number {
  font-size: 14px;
  color: #606266;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 8px;
  font-size: 18px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item.address {
  grid-column: span 2;
}

.info-item.full-width {
  grid-column: span 2;
}

.label {
  font-weight: bold;
  width: 80px;
  flex-shrink: 0;
}

.value {
  flex: 1;
  word-break: break-all;
}

.price-summary {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.price-item.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e4e7ed;
  font-weight: bold;
}

.highlight {
  color: #f56c6c;
  font-size: 16px;
}

.dialog-footer {
  padding: 10px 20px 20px;
  text-align: right;
}

.price {
  color: #e6a23c;
  font-weight: 500;
}

/* 重写对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-select-dropdown__item) {
  padding: 0 20px;
}
</style> 